
function renderReplaceTemp(template, ctx){
    let reg = /{{(.*?)}}/g

    let res = template.replace(reg, (item, key) => {
        const fields = key.split(".")
        const data = fields.reduce((current,key)=>{
            try{
                return current[key]
            }catch (e) {
                return {}
            }
        },ctx)
        return data || ''
    })

    return res
}

function renderWatch(layoutComponent) {
    return ""
}


function renderComputed(layoutComponent) {

    return `
        count(){
            return 1;
        }
    `

}


function renderMethod(layoutComponent) {
    return `
        add(){
            
        }
    `
}


function relyOn(layoutComponent) {
    return ""
}

/**
 * 生成 组件依赖
 * @param layoutComponent
 * @returns {string}
 */
function renderProps(layoutComponent) {
    return Object.keys(layoutComponent.__field_props__)
        .map(key=>{
        if(layoutComponent.__field_props__[key].value !== layoutComponent.__field_props__[key].defaultValue){
            if(layoutComponent.__field_props__[key].effect === 'prop'){
                if(layoutComponent.__field_props__.type === 'string'){
                    return `${key}="${layoutComponent.__field_props__[key].value}"`
                }else{
                    return `:${key}="${layoutComponent.__field_props__[key].value}"`
                }
            }

        }
        return ''
    })
        .concat(layoutComponent.__config__.field.value !== layoutComponent.__config__.field.defaultValue?`v-model="${layoutComponent.__config__.field.value}"`:'')
        .join(" ")
}


/**
 * 将每一项数据进行数据组件
 * @param layoutComponent
 * @param ctx
 */
function renderComponent(layoutComponent,ctx) {
    ctx.template.push(renderReplaceTemp(layoutComponent.antd, {props: renderProps(layoutComponent)}))
    ctx.import.push(relyOn(layoutComponent))
    // ctx.data.push()
    ctx.methods.push(renderReplaceTemp(layoutComponent.method, layoutComponent))
    ctx.computed.push(renderComputed(layoutComponent))
    ctx.watch.push(renderWatch(layoutComponent))
}


/**
 * 生成代码结构
 * @param layouts 生成代码的json数据
 * @returns
 */
export default function generator(layouts) {
    const ctx = {
        template:[],
        import:[],
        data:[],
        methods:[],
        computed:[],
        watch:[],
    }
    layouts.map(item=>renderComponent(item,ctx))
    return `
        <template>
            <div>
               ${ctx.template.join("")}
            </div>
        </template>
        <script>
            ${ctx.import.join("\n")}
            export default {
                methods:{
                    ${ctx.methods.join(",\n")}
                },
                computed:{
                    ${ctx.computed.join(",\n")}
                },
                watch:{
                    ${ctx.computed.join(",\n")}
                }
            }
        
        </script>
    `
}
